<template>
  <div v-loading="loading">
    <div class="report-action">
      <el-button type="primary" :loading="printLoading" @click="printPage">
        <i class="fa fa-print"></i>
        打印
      </el-button>
      <el-button
        icon="el-icon-download"
        type="primary"
        :loading="printLoading"
        @click="exportToExcel"
      >
        导出
      </el-button>
    </div>
    <div class="report-wrap">
      <div :id="printId">
        <table class="table text-center">
          <tbody>
            <tr>
              <td class="border-0" colspan="6" data-font='{"sz": 16, "bold": true}'>
                <h4 class="report-title">《“民宿纾困贷”申请表》</h4>
              </td>
            </tr>
          </tbody>
        </table>
        <table class="table table-bordered table-sm bg-white table-vertical-middle text-center">
          <colgroup>
            <col width="16%" />
            <col width="20%" />
            <col width="14%" />
            <col width="20%" />
            <col width="14%" />
            <col width="16%" />
          </colgroup>
          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              一、经营主体信息
            </td>
          </tr>
          <tr>
            <td>主体名称</td>
            <td>{{ related.customer_name }}</td>
            <td>营业执照号</td>
            <td>{{ related.register_no }}</td>
            <td>组织类型</td>
            <td>{{ related.org_class_str }}</td>
          </tr>
          <tr>
            <td>经营地址</td>
            <td colspan="5" class="text-left pl-3">{{ related.address }}</td>
          </tr>
          <tr>
            <td>经营者姓名</td>
            <td>{{ related.corp_name }}</td>
            <td>身份证号</td>
            <td>{{ related.lender_idcard }}</td>
            <td>联系电话</td>
            <td>{{ related.mobile_no }}</td>
          </tr>
          <tr>
            <td>身份证地址</td>
            <td colspan="5" class="text-left pl-3">{{ related.cert_address }}</td>
          </tr>

          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              二、民宿经营信息
            </td>
          </tr>
          <tr>
            <td>民宿位置</td>
            <td>{{ hotel.address }}</td>
            <td>民宿区域位置</td>
            <td>{{ enumAreaPosType[hotel.area_pos_type || ''] }}</td>

            <td>经营场所是否自有</td>
            <td>{{ enumBusPlaceType[hotel.bus_place_type || ''] }}</td>
          </tr>
          <tr>
            <td>周边自然景观资源</td>
            <td colspan="5">{{ enumLandResourceType[hotel.land_resource_type || ''] }}</td>
          </tr>
          <tr>
            <td>民宿经营期限</td>
            <td>{{ hotel.bussiness_months || '-' }} 月</td>
            <td>用工人数</td>
            <td>{{ hotel.emp_total || '-' }} 人</td>
            <td>近一年人工支出</td>
            <td>{{ hotel.emp_pay || '-' }} 万元</td>
          </tr>
          <tr>
            <td>客房总数</td>
            <td>{{ hotel.house_total || '-' }} 间</td>
            <td>占地面积</td>
            <td>{{ hotel.area_covered || '-' }} ㎡</td>
            <td>建筑面积</td>
            <td>{{ hotel.area_build }} ㎡</td>
          </tr>
          <tr>
            <td colspan="3">年销售收入（近5年）</td>
            <td colspan="3">年经营成本（近5年）</td>
          </tr>
          <tr>
            <td>年份</td>
            <td colspan="2">金额（万元）</td>
            <td>年份</td>
            <td colspan="2">金额（万元）</td>
          </tr>
          <template
            v-for="index in Math.max(
              hotelDetail.saleIncomeList.length,
              hotelDetail.businessCostList.length
            )"
          >
            <tr :key="`1-${index}`">
              <td>
                <span v-if="index - 1 >= 0 && hotelDetail.saleIncomeList.length > index - 1">
                  {{ hotelDetail.saleIncomeList[index - 1].operate_time || '-' }}
                </span>
              </td>
              <td colspan="2">
                <span v-if="index - 1 >= 0 && hotelDetail.saleIncomeList.length > index - 1">
                  {{ hotelDetail.saleIncomeList[index - 1].operate_value || '-' }}
                </span>
              </td>
              <td>
                <span v-if="index - 1 >= 0 && hotelDetail.businessCostList.length > index - 1">
                  {{ hotelDetail.businessCostList[index - 1].operate_time || '-' }}
                </span>
              </td>
              <td colspan="2">
                <span v-if="index - 1 >= 0 && hotelDetail.businessCostList.length > index - 1">
                  {{ hotelDetail.businessCostList[index - 1].operate_value || '-' }}
                </span>
              </td>
            </tr>
          </template>
          <tr>
            <td>平均每年</td>
            <td colspan="2">{{ hotelDetail.saleIncomeAverage || '-' }}</td>
            <td>平均每年</td>
            <td colspan="2">{{ hotelDetail.businessCostAverage || '-' }}</td>
          </tr>
          <tr>
            <td colspan="3">客房均定价（近12月）</td>
            <td colspan="3">月入住率（近12月）</td>
          </tr>
          <tr>
            <td>日期</td>
            <td colspan="2">金额（元）</td>
            <td>日期</td>
            <td colspan="2">入住率（%）</td>
          </tr>
          <template
            v-for="index in Math.max(
              hotelDetail.housePriceList.length,
              hotelDetail.inHouseRateList.length
            )"
          >
            <tr :key="`2-${index}`">
              <td>
                <span v-if="index - 1 >= 0 && hotelDetail.housePriceList.length > index - 1">
                  {{ hotelDetail.housePriceList[index - 1].operate_time || '-' }}
                </span>
              </td>
              <td colspan="2">
                <span v-if="index - 1 >= 0 && hotelDetail.housePriceList.length > index - 1">
                  {{ hotelDetail.housePriceList[index - 1].operate_value || '-' }}
                </span>
              </td>
              <td>
                <span v-if="index - 1 >= 0 && hotelDetail.inHouseRateList.length > index - 1">
                  {{ hotelDetail.inHouseRateList[index - 1].operate_time || '-' }}
                </span>
              </td>
              <td colspan="2">
                <span v-if="index - 1 >= 0 && hotelDetail.inHouseRateList.length > index - 1">
                  {{ hotelDetail.inHouseRateList[index - 1].operate_value || '-' }}
                </span>
              </td>
            </tr>
          </template>
          <tr>
            <td>平均每月</td>
            <td colspan="2">{{ hotelDetail.housePriceAverage || '-' }}</td>
            <td>平均每月</td>
            <td colspan="2">{{ hotelDetail.inHouseRateAverage || '-' }}</td>
          </tr>
          <tr>
            <td>内部环境照片</td>
            <td colspan="5">
              <div class="d-flex flex-wrap">
                <img
                  v-for="(img, index) in inEnvImages"
                  @click="handlePreview(inEnvImages, index)"
                  class="attach-item-img m-2"
                  :key="index"
                  :src="img"
                  alt="附件图片"
                  height="100"
                  width="100"
                />
              </div>
            </td>
          </tr>
          <tr>
            <td>外部环境照片</td>
            <td colspan="5">
              <div class="d-flex flex-wrap">
                <img
                  v-for="(img, index) in outEnvImages"
                  @click="handlePreview(outEnvImages, index)"
                  class="attach-item-img m-2"
                  :key="index"
                  :src="img"
                  alt="附件图片"
                  height="100"
                  width="100"
                />
              </div>
            </td>
          </tr>

          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              三、项目资金投入情况及资金来源情况
            </td>
          </tr>
          <tr>
            <td class="text-left" colspan="6">（一）、项目投入</td>
          </tr>
          <tr>
            <td>土地流转</td>
            <td>{{ hotel.land_cir || '-' }} 万元</td>
            <td>基础设施建设</td>
            <td>{{ hotel.base_buid || '-' }} 万元</td>
            <td>房屋建筑及装修</td>
            <td>{{ hotel.house_fix || '-' }} 万元</td>
          </tr>
          <tr>
            <td>运营资金投入</td>
            <td>{{ hotel.operate_funds || '-' }} 万元</td>
            <td>其它投入</td>
            <td colspan="3">{{ hotel.other_operate_funds || '-' }} 万元</td>
          </tr>
          <tr>
            <td class="text-left" colspan="6">（二）、资金来源</td>
          </tr>
          <tr>
            <td>自有资金</td>
            <td>{{ hotel.self_funds || '-' }} 万元</td>
            <td>银行借款</td>
            <td>{{ hotel.load_funds || '-' }} 万元</td>
            <td>其它借款</td>
            <td>{{ hotel.other_funds || '-' }} 万元</td>
          </tr>
          <tr>
            <td>项目扶持</td>
            <td>{{ hotel.project_support_funds || '-' }} 万元</td>
            <td>其它资金来源</td>
            <td colspan="3">{{ hotel.other_support_funds || '-' }} 万元</td>
          </tr>

          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              四、个人/企业不动产信息
            </td>
          </tr>
          <tr>
            <td>资产名称</td>
            <td>购买金额</td>
            <td>权利人</td>
            <td>是否有证</td>
            <td colspan="2">资产地址</td>
          </tr>
          <tr v-for="p of immov" :key="p.id">
            <td>{{ p.immov_name || '-' }}</td>
            <td>{{ p.buy_funds || '-' }} 万元</td>
            <td>{{ p.own_person || '-' }}</td>
            <td>{{ +(p.is_cert || 0) === 1 ? '是' : '否' }}</td>
            <td colspan="2">{{ p.immov_address || '-' }}</td>
          </tr>
          <tr v-show="!immov.length">
            <td class="text-center p-3 text-muted" colspan="6">暂无数据</td>
          </tr>

          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              五、银行贷款情况
            </td>
          </tr>
          <tr>
            <td>借款人姓名</td>
            <td>贷款银行</td>
            <td>贷款余额</td>
            <td>贷款品种</td>
            <td>贷款期限</td>
            <td>信用状况</td>
          </tr>
          <tr v-for="p of loanData" :key="p.id">
            <td>{{ p.loan_person || '-' }}</td>
            <td>{{ p.bank_name || '-' }}</td>
            <td>{{ p.loan_left_funds || '-' }} 万元</td>
            <td>{{ p.loan_category || '-' }}</td>
            <td>{{ p.loan_period || '-' }}</td>
            <td>{{ p.credit_info || '-' }}</td>
          </tr>
          <tr v-show="!loanData.length">
            <td class="text-center p-3 text-muted" colspan="6">暂无数据</td>
          </tr>

          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              六、经营主体股东及其家庭主要成员信息
            </td>
          </tr>
          <tr>
            <td>姓名</td>
            <td>性别</td>
            <td>与贷款人关系</td>
            <td>证件号码</td>
            <td>联系电话</td>
            <td>职业</td>
          </tr>
          <tr v-for="p of personData" :key="p.id">
            <td>{{ p.person_name || '-' }}</td>
            <td>{{ p.sex || '-' }}</td>
            <td>{{ p.relate || '-' }}</td>
            <td>{{ p.id_card || '-' }}</td>
            <td>{{ p.mobile_no || '-' }}</td>
            <td>{{ p.occupation || '-' }}</td>
          </tr>
          <tr v-show="!personData.length">
            <td class="text-center p-3 text-muted" colspan="6">暂无数据</td>
          </tr>
          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              七、用电信息
            </td>
          </tr>
          <tr>
            <td>电表户号</td>
            <td>{{ eleInfo.ele_no || '-' }}</td>
            <td>开户电话</td>
            <td>{{ eleInfo.mobile_no || '-' }}</td>
            <td>开户户名</td>
            <td>{{ eleInfo.account_no || '-' }}</td>
          </tr>
          <tr>
            <td class="text-left font-weight-bold" data-font-bold="true" colspan="6">
              八、资金需求
            </td>
          </tr>
          <tr>
            <td>申请金额</td>
            <td>{{ related.apply_funds || '-' }} 万元</td>
            <td>贷款期限</td>
            <td>{{ related.months || '-' }} 月</td>
            <td>贷款用途</td>
            <td>{{ related.funds_use_dir || '-' }}</td>
          </tr>
          <tr>
            <td class="font-weight-bold" data-font-bold="true" colspan="6">评级结果</td>
          </tr>
          <tr>
            <td colspan="6" class="p-5">
              <div class="rating-level">{{ ratingLevel }}</div>
              <el-rate
                v-model="ratingValue"
                :max="8"
                disabled
                :colors="['#da272b', '#da272b', '#da272b']"
              ></el-rate>
              <p class="my-3">
                <span>经系统初步测算，你的贷款评级结果为</span>
                <span class="px-2">{{ ratingLevel }}</span>
                <span>，授信额度为</span>
                <span class="px-2">{{ ratingFunds }}</span>
                <span>万元，最终授信金额以银行和担保公司调查核实后审批为准。</span>
              </p>
              <p class="text-muted">
                若有疑问请联系市财农担保公司业务部，联系电话：0856-5281988。公司地址市财政局内1楼。
              </p>
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
export const enumAreaPosType = {
  1: '（1）处于客流量集中地带，或旅游园区内',
  2: '（2）处于客流量集中地带附近，或旅游园区周边',
  3: '（3）客流量稀疏,或离旅游园区较远',
}

export const enumLandResourceType = {
  1: '（1）周边1公里内有名胜景区、5A景区、自然生态保护区或少数民族聚居区等优质自然、人文旅游资源',
  2: '（2）周边1公里内有4A景区，或较好的景观资源',
  3: '（3）周边1公里内景观资源一般',
  4: '（4）周边1公里内景观资源较差',
}

export const enumBusPlaceType = {
  1: '（1）经营场所为借款人家庭自有',
  2: '（2）经营场所为租赁或非借款人家庭自有',
}

import { arrayFromString, add, printA4, excelTablesExport } from '@vimi/utils-tool'
export default {
  components: {},
  props: {
    queryId: String,
  },
  data() {
    return {
      enumAreaPosType,
      enumLandResourceType,
      enumBusPlaceType,
      loading: false,
      related: {},
      relatedTable: 'credit_industrial_apply',
      hotel: {},
      hotelTable: 'credit_industrial_hotel',
      hotelDetail: {
        saleIncomeList: [], //年销售收入（近5年）
        saleIncomeAverage: 0,
        businessCostList: [], //年经营成本（近5年）
        businessCostAverage: 0,
        housePriceList: [], //客房均定价（近12月）
        housePriceAverage: 0,
        inHouseRateList: [], //月入住率（近12月）
        inHouseRateAverage: 0,
      },
      hotelDetailTable: 'credit_industrial_hotel_detail',

      immov: [],
      immovTable: 'credit_industrial_immov',
      loanData: [],
      loanTable: 'credit_industrial_loan',

      personData: [],
      personTable: 'credit_industrial_person',
      eleInfo: {},
      eleTable: 'credit_industrial_ele',

      rating: {},
      ratingValue: null,

      printLoading: false,
    }
  },
  computed: {
    inEnvImages() {
      return arrayFromString(this.hotel.attachment_inner)
    },
    outEnvImages() {
      return arrayFromString(this.hotel.attachment_outer)
    },
    ratingLevel() {
      return this.rating?.levelInfo?.score_level ?? ''
    },
    ratingFunds() {
      return this.rating?.levelInfo?.measure_result ?? ''
    },
    printId() {
      return this.queryId + 'apply-table'
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handlePreview(images, index) {
      this.$utils.viewer({
        images: images,
        index,
      })
    },
    getData() {
      this.loading = true
      Promise.all([
        this.getRelated(),
        this.getHotel(),
        this.getHotelDetail(),
        this.getImmov(),
        this.getLoanData(),
        this.getPerson(),
        this.getEle(),
        this.getRating(),
      ])
        .then(
          ([
            relatedRes,
            hotelRes,
            hotelDetailRes,
            immovRes,
            loanRes,
            personRes,
            eleRes,
            ratingRes,
          ]) => {
            this.related = relatedRes?.data ?? {}
            this.hotel = hotelRes?.data?.[0] ?? {}
            this.handleDetail(hotelDetailRes?.data ?? [])
            this.immov = immovRes?.data ?? []
            this.loanData = loanRes?.data ?? []
            this.personData = personRes?.data ?? []
            this.eleInfo = eleRes?.data?.[0] ?? {}
            this.rating = ratingRes?.data ?? {}
            const enumLevel = {
              'A++': 8,
              'A+': 7,
              A: 6,
              B: 5,
              C: 4,
              D: 3,
              E: 2,
              F: 1,
            }
            this.ratingValue = enumLevel[this.rating?.levelInfo?.score_level ?? ''] ?? null
          }
        )
        .finally(() => {
          this.loading = false
        })
    },
    handleDetail(data) {
      this.hotelDetail = {
        saleIncomeList: [],
        saleIncomeAverage: 0,
        businessCostList: [],
        businessCostAverage: 0,
        housePriceList: [],
        housePriceAverage: 0,
        inHouseRateList: [],
        inHouseRateAverage: 0,
      }
      let saleAll = 0
      let businessCostAll = 0
      let housePriceAll = 0
      let inHouseRateAll = 0
      for (const d of data) {
        const type = +d.operate_type
        switch (type) {
          case 1:
            saleAll = add(saleAll, d.operate_value)
            this.hotelDetail.saleIncomeList.push(d)
            break
          case 2:
            businessCostAll = add(businessCostAll, d.operate_value)
            this.hotelDetail.businessCostList.push(d)
            break
          case 3:
            housePriceAll = add(housePriceAll, d.operate_value)
            this.hotelDetail.housePriceList.push(d)
            break
          case 4:
            inHouseRateAll = add(inHouseRateAll, d.operate_value)
            this.hotelDetail.inHouseRateList.push(d)
            break
          default:
            break
        }
      }
      this.hotelDetail.saleIncomeAverage =
        Math.round((saleAll * 100) / this.hotelDetail.saleIncomeList.length) / 100
      this.hotelDetail.businessCostAverage =
        Math.round((businessCostAll * 100) / this.hotelDetail.businessCostList.length) / 100
      this.hotelDetail.housePriceAverage =
        Math.round((housePriceAll * 100) / this.hotelDetail.housePriceList.length) / 100
      this.hotelDetail.inHouseRateAverage =
        Math.round((inHouseRateAll * 100) / this.hotelDetail.inHouseRateList.length) / 100
    },
    getRelated() {
      return this.$api
        .getDataFromId(this.$serviceName, this.relatedTable, this.queryId)
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getHotel() {
      return this.$api
        .getData(this.$serviceName, this.hotelTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getHotelDetail() {
      return this.$api
        .getData(this.$serviceName, this.hotelDetailTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getImmov() {
      return this.$api
        .getData(this.$serviceName, this.immovTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getLoanData() {
      return this.$api
        .getData(this.$serviceName, this.loanTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getPerson() {
      return this.$api
        .getData(this.$serviceName, this.personTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getEle() {
      return this.$api
        .getData(this.$serviceName, this.eleTable, {
          'customer_related_id.eq': this.queryId,
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    getRating() {
      return this.$http
        .get('/api/xyd/view/getRatingInfo', {
          params: {
            model_key: 'hotel',
            customer_related_id: this.queryId,
          },
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '请求失败，请重试！')
        })
    },
    printPage() {
      printA4(
        document.getElementById(this.printId).innerHTML,
        `
    .report-title {text-align: center;margin-bottom: 1rem;font-weight: bold;font-size: 1.5rem;line-height: 1.5;}
    .table-bordered td {border-color: #333 !important;padding: 0.25rem;text-align: center;vertical-align: middle;}
    .rating-level {font-size: 4rem; font-weight: bold;color: var(--primary);
}
  `
      )
    },
    exportToExcel() {
      excelTablesExport(this.printId, `申请表-${this.related.customer_name}`, {
        emptyRows: 1,
        styles: {
          // 全局样式
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        // 单元格样式，最顶级设置(styles -> dataset -> cellStyles)
        // 可以设置成 A1，或 'r-c' 的主键
        cellStyles: {},
      })
    },
  },
}
</script>

<style lang="scss" scoped>
$report-width: 100%;
$report-input-border-color: #333;
.table-vertical-middle td {
  vertical-align: middle;
}
.report-wrap {
  width: $report-width;
  margin: 0 auto;
  padding: 2rem;
  border: 1px solid #e9ecef;
  border-radius: 2px;
  background-color: #fff;

  .report-title {
    text-align: center;
    margin-bottom: 1rem;
    font-weight: bold;
    font-size: 1.45rem;
  }
}
.report-action {
  width: $report-width;
  margin: 0 auto 0.5rem auto;
  text-align: right;
}

.table-bordered td {
  border: 1px solid;
  border-color: #333;
  padding: 0.25rem;
  text-align: center;
  vertical-align: middle;

  &.report-input-last-td {
    border-right-color: $report-input-border-color;
  }

  &.report-input-td {
    border-color: $report-input-border-color;
    background-color: #ffffee;
    padding: 0;

    .form-control {
      border: none;
      background-color: #ffffee;
      padding: 0.25rem;
    }
  }
}
.attach-item-img {
  border-radius: 2px;
  z-index: 1;
  cursor: pointer;
}

.rating-level {
  font-size: 4rem;
  font-weight: bold;
  color: var(--primary);
}
</style>
